/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.chl.dat076.datesite.controllers;

import edu.chl.dat076.datesite.ejbs.UserEJBLocal;
import edu.chl.dat076.datesite.entities.SiteUser;
import java.io.Serializable;
import java.util.Calendar;
import java.util.Date;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;

/**
 *
 * @author Mikey
 */

@ManagedBean
@ViewScoped
public class MyProfileBackingBean implements Serializable {
  
    @EJB
    private UserEJBLocal userJPACtrl;

    private SiteUser user;
    
    private int day;
    private int month;
    private int year;
    
    @PostConstruct
    public void postConstruct () {
        user = userJPACtrl.getUser(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user").toString());
        Date bdate = user.getUserProperties().getBirthDate();
        Calendar cal = Calendar.getInstance();
        cal.setTime(bdate);
        day = cal.get(Calendar.DAY_OF_MONTH);
        month = cal.get(Calendar.MONTH);
        year = cal.get(Calendar.YEAR);
    }

    public int getDay() {
        return day;
    }

    public void setDay(int day) {
        this.day = day;
    }

    public int getMonth() {
        return month;
    }

    public void setMonth(int month) {
        this.month = month;
    }

    public int getYear() {
        return year;
    }

    public void setYear(int year) {
        this.year = year;
    }
    
    public SiteUser getUser () {
        return user;
    }
    
    public String saveProfile() {
        
        try {
            Calendar newDateCalendar = Calendar.getInstance();
            newDateCalendar.set(year, month, day);
            Date newBirthDate = newDateCalendar.getTime();
            user.getUserProperties().setBirthDate(newBirthDate);
            userJPACtrl.editUser(user);
            FacesContext.getCurrentInstance().addMessage("Update", new FacesMessage("Your profile has been updated.")); 
        }
        catch (Exception e) {
            FacesContext.getCurrentInstance().addMessage("Fail", new FacesMessage("Failed to update your profile."));
        }
        return "updateProfile";
    }
}
